import { defineStore } from 'pinia';
import { reactive, ref } from 'vue';
import type { EnhancedRouteLocation } from '@/router/types';
import type { RouteRecordName } from 'vue-router';

const useRouteCacheStore = defineStore('routeCache', () => {
  // 需要缓存的组件名列表
  const routeCaches = ref<RouteRecordName[]>([]);

  // 页面滚动位置记录 - 使用 reactive 或 Map
  const scrollPositions = reactive(new Map<string, number>());

  // 添加缓存
  const addRouteCache = (route: EnhancedRouteLocation): void => {
    if (routeCaches.value.includes(route.name)) {
      return;
    }
    if (route?.meta?.keepAlive) {
      routeCaches.value.push(route.name);
    }
  };
  const removeCache = (routeName: string): void => {
    routeCaches.value = routeCaches.value.filter((name) => name !== routeName);
  };

  // 保存滚动位置
  const saveScrollPosition = (routeName: string, position: number): void => {
    scrollPositions.set(routeName, position);
  };
  // 获取滚动位置
  const getScrollPosition = (routeName: string): number => {
    return scrollPositions.get(routeName) || 0;
  };

  // 清空所有缓存
  const clearAllCache = (): void => {
    routeCaches.value = [];
    scrollPositions.clear();
  };

  // 清除指定页面的缓存和滚动位置
  const clearCacheForPage = (routeName: string): void => {
    removeCache(routeName);
    scrollPositions.delete(routeName);
  };

  // 检查是否已缓存
  const hasCache = (routeName: string): boolean => {
    return routeCaches.value.includes(routeName);
  };

  return {
    routeCaches,
    addRouteCache,
    getScrollPosition,
    saveScrollPosition,
    clearAllCache,
    clearCacheForPage,
    hasCache,
  };
});

export default useRouteCacheStore;
